package com.digua.base.socket.request

import org.java_websocket.client.WebSocketClient
import org.java_websocket.framing.PingFrame
import org.java_websocket.framing.PongFrame
import java.util.ArrayDeque
import java.util.Queue

class PongRequest : Request<PingFrame> {
    private val PONG_POOL: Queue<PongFrame> = ArrayDeque(7)

    private var pingFrame: PingFrame? = null

    override fun setRequestData(data: PingFrame) {
        pingFrame = data
    }

    override fun getRequestData(): PingFrame? = pingFrame

    override fun send(client: WebSocketClient?) {
        val pongFrame = getPongFrame()
        if (pingFrame != null) {
            pongFrame.setPayload(pingFrame!!.payloadData)
            pingFrame = null
        } else {
            pongFrame.setPayload(null)
        }
        client?.sendFrame(pongFrame)
        offerPongFrame(pongFrame)
    }

    override fun release() {
        RequestFactory.releasePongRequest(this)
    }

    override fun toString() = "[@PongRequest${hashCode()},PingFrame:${pingFrame?.toString() ?: "null"}]"

    private fun getPongFrame(): PongFrame {
        var pongFrame = PONG_POOL.poll()
        if (pongFrame == null) {
            pongFrame = PongFrame()
        }
        return pongFrame
    }

    private fun offerPongFrame(pongFrame: PongFrame) {
        pingFrame = null
        PONG_POOL.offer(pongFrame)
    }
}